<script setup>
import { reactive, ref, computed, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from 'vue-router'
import { removeToken } from "@/composables/cookie";
import { showMessage, showModel } from "@/composables/util.js";
import { updatePassword, updateUserInfo, collectCourse, cancelCollectCourse, isCollected } from "@/api/common/user"
import { uploadFile } from "@/api/common/file"
import { findVideoDetail } from "@/api/common/index"
import { addOrder } from "@/api/common/order"
import { Star, StarFilled } from '@element-plus/icons-vue'
import XGPlayer from 'xgplayer'
import 'xgplayer/dist/index.min.css'; // 引入css
import moment from 'moment'

// 从浏览器本地存储中取出用户信息
let userInfo = JSON.parse(localStorage.getItem("userInfo"))
const route = useRoute()
const router = useRouter()
// 控制个人信息弹出框
let info = ref(false)
let password = ref(false)
// 设置导航栏激活项
const activeIndex = ref('3')
const form1 = reactive({
  id: null,
  username: null,
  avatar: null,
  token: null
})
const form2 = reactive({
  username: '',
  password: '',
  newPassword: '',
  surePassword: ''
})
onMounted(() => {
    if(userInfo !== null) {
      form1.id = userInfo.id
      form1.username = userInfo.username
      form1.avatar = userInfo.avatar
      form1.token = userInfo.token
      form2.username = userInfo.username
    }
    // 在组件挂载后获取视频详情
    refreshVideoDetail(route.params.id)
})
const handleAvatarChange = (file) => {
  // 创建表单对象
  let formData = new FormData()
  formData.append('file', file.raw)
  // 调用后台文件上传接口
  uploadFile(formData).then((e) => {
    // 响参失败，提示错误消息
    if (e.data.success == false) {
      let message = e.message
      showMessage(message, 'error')
      return
    }
    // 成功则设置头像链接，并提示成功
    form1.avatar = e.data.data
    console.log("头像地址："+form1.avatar)
  })
}
// 修改用户信息
const saveInfo = () => {
  // 调用后端修改用户信息接口
  updateUserInfo(form1).then((res) => {
    if(res.data.success === true){
      // 提示修改成功
      showMessage('修改成功')
      // 更新存储的用户信息JSON格式到Local Storage(浏览器本地存储) 中
      localStorage.setItem("userInfo", JSON.stringify(res.data.data))
      // 更新之前获取的用户信息变量
      userInfo = JSON.parse(localStorage.getItem("userInfo"))
      info = false
      window.location.reload();
    }else {
      let message = res.data.message
      console.log(message)
      // 提示消息
      showMessage(message, 'error')
    }
  })
}

// 修改用户密码
const savePassword = () => {
  // 调用后端修改用户信息接口
  updatePassword(form2).then((res) => {
    if(res.data.success === true){
      // 提示修改成功
      showMessage('修改成功')
      // 删除cookie中的token
      removeToken()
      // 删除Local Storage中的userInfo
      localStorage.removeItem('userInfo')
      // 重新跳转登录页面
      router.push('/login')
    }else {
      let message = res.data.message
      console.log(message)
      // 提示消息
      showMessage(message, 'error')
    }
  })

}
// 退出登录方法
const logout = () => {
    showModel('是否退出登录?').then(() => {
        // 删除cookie中的token
        removeToken()
        // 删除Local Storage中的userInfo
        localStorage.removeItem('userInfo')
        showMessage('退出登录成功!')
        // 跳转登录页
        router.push('/login')
    })
}
function goIndex() {
    router.push({ path: '/' })
}
function goLogin() {
    router.push({ path: '/login' })
}
function goOrder() {
    router.push('/order')
}
function goCollect() {
  router.push('/collect')
}
// 视频数据
const video = ref({})

// 获取视频详情
async function refreshVideoDetail(id) {
    try {
        const res = await findVideoDetail({ 
            courseId: id, 
            type: 1, 
            userId: userInfo ? userInfo.id : null 
        })
        if (res.data.success) {
            video.value = res.data.data
            console.log("视频数据", video.value)
            // 检查是否是付费课程且用户未登录
            if (video.value.price > 0 && !userInfo) {
                showMessage('请先登录后再查看付费课程', 'warning')
                router.push('/login')
                return
            }
            // 在获取视频详情后检查收藏状态
            if (userInfo) {
                await checkIsCollected()
            }
            // 初始化播放器
            player = new XGPlayer({
                id: 'h5player',
                el: playerRef.value,
                url: video.value.location,
                poster: video.value.cover,
                autoplay: false,
                fluid: true,
                lang: 'zh-cn',
                playbackRate: [0.5, 1.0, 1.5, 2.0],
                controlPlugins: ['progressPreview']
            })
        }
    } catch (error) {
        console.error('获取视频详情失败:', error)
    }
}

// 播放器实例
let player = null
const playerRef = ref(null)

onUnmounted(() => {
    player && player.destroy()
})

// 订单相关状态
const orderForm = reactive({
    courseId: video.value.id,
    number: null,
    type: 1,
    orderTime: null,
    price: video.value.price,
    userId: userInfo ? userInfo.id : null
})
const isSubmitting = ref(false)

// 生成订单编号（网页1+网页3优化）
const generateOrderNo = () => {
    const timestamp = new Date().getTime()
    const random = Math.floor(Math.random() * 1000000)
    orderForm.number = `${timestamp}_${random}`
    console.log("订单数据" + JSON.stringify(orderForm))
    return orderForm.number
}

function orderSumbit() {
    console.log("进入orderSumbit")
    console.log("文章详情数据" + JSON.stringify(video.value.id))
    orderForm.courseId = video.value.id
    orderForm.price = video.value.price
    console.log("订单1详情1数据" + JSON.stringify(orderForm))
    // 调用后台分页接口，并传入所需参数
    addOrder(orderForm)
        .then((res) => {
            if (res.data.success == true) {
                showMessage('成功下单')
                // 跳转我的订单页面
                goOrder()
            } else {
                let message = res.data.message
                console.log(message)
                // 提示消息
                showMessage(message, 'error')
            }
        })
}

// 收藏相关
const isCollectedState = ref(false)

// 检查是否已收藏
const checkIsCollected = async () => {
    if (!userInfo) return
    try {
        const res = await isCollected({
            userId: userInfo.id,
            courseId: route.params.id,
            type: 1
        })
        if (res.data.success) {
            isCollectedState.value = res.data.data
            console.log('收藏状态:', isCollectedState.value)
        }
    } catch (error) {
        console.error('检查收藏状态失败:', error)
    }
}

// 收藏/取消收藏
const toggleCollect = async () => {
  if (!userInfo) {
    showMessage('请先登录!', 'warning')
    return
  }

  const params = {
    userId: userInfo.id,
    courseId: video.value.id,
    type: 1
  }

  try {
    const res = await (isCollectedState.value ? cancelCollectCourse(params) : collectCourse(params))
    if (res.data.success) {
      isCollectedState.value = !isCollectedState.value
      showMessage(isCollectedState.value ? '收藏成功' : '已取消收藏')
    }
  } catch (error) {
    console.error('操作失败:', error)
    showMessage('操作失败，请重试', 'error')
  }
}
</script>

<template>
    <!-- 主容器使用Element布局 -->
    <el-container class="home-container">
        <!-- 导航栏 -->
        <el-header class="header">
            <div class="nav-container">
                <div class="logo">
                    高校<span class="blue">互联网技术</span>在线学习平台
                </div>
                <el-menu mode="horizontal" :default-active="activeIndex">
                    <el-menu-item index="1">
                        <router-link to="/">首页</router-link>
                    </el-menu-item>
                    <el-menu-item index="2">
                        <router-link to="/article-course">图文课程</router-link>
                    </el-menu-item>
                    <el-menu-item index="3">
                        <router-link to="/video-course">视频课程</router-link>
                    </el-menu-item>
                </el-menu>
                <div class="search-box">
                    <el-input placeholder="搜索课程..." suffix-icon="Search" class="search-input" />
                </div>
                <!-- 未登录状态 -->
                <div class="user-wrapper" v-if="!userInfo">
                    <el-button type="primary" class="login-btn" @click="goLogin" round>
                        <i class="el-icon-user"></i>
                        <span>登录 / 注册</span>
                    </el-button>
                </div>

                <!-- 已登录状态 -->
                <div class="user-panel" v-else>
                    <el-dropdown trigger="hover">
                        <div class="user-card">
                            <div class="profile">
                                <el-avatar :src="userInfo.avatar" :size="36" class="user-avatar"
                                    :style="{ backgroundColor: '#8ac8ff' }" />
                            </div>
                        </div>

                        <!-- 下拉菜单 -->
                        <template #dropdown>
                            <el-dropdown-menu class="user-menu">
                                <el-dropdown-item class="menu-item" @click="info = true">
                                    <i class="el-icon-user-solid"></i>个人信息
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="goOrder">
                                    <i class="el-icon-time"></i>我的订单
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="goCollect">
                                    <i class="el-icon-star-off"></i>我的收藏
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="password = true">
                                    <i class="el-icon-lock"></i>修改密码
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item logout" @click="logout">
                                    <i class="el-icon-switch-button"></i>退出登录
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>
        </el-header>
        <!-- 视频详情主体 -->
        <el-main>

            <!-- 未购买状态显示支付页面 -->
            <div v-if="video.isShow === 0 && userInfo" class="payment-container">
                <el-card class="order-card">
                    <!-- 订单标题 -->
                    <template #header>
                        <div class="card-header">
                            <h2 style="font-size: 30px;">课程下单</h2>
                        </div>
                    </template>

                    <!-- 订单信息 -->
                    <el-descriptions :column="1" border>
                        <el-descriptions-item label="课程名称">
                            {{ video.title }}
                        </el-descriptions-item>
                        <el-descriptions-item label="订单编号">
                            {{ orderForm.number || generateOrderNo() }}
                        </el-descriptions-item>
                        <el-descriptions-item label="应付金额">
                            <span class="price">¥{{ video.price?.toFixed(2) }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="下单用户">
                            <span class="username">{{ userInfo?.username }}</span>
                        </el-descriptions-item>
                    </el-descriptions>

                    <!-- 操作按钮 -->
                    <div class="action-buttons">
                        <el-button type="primary" @click="orderSumbit" :loading="isSubmitting">
                            {{ isSubmitting ? '提交中...' : '立即下单' }}
                        </el-button>
                        <el-button @click="goIndex">返回</el-button>
                    </div>
                </el-card>
            </div>

            <div v-show="video.isShow === 1" class="video-detail">
                <!-- 视频播放容器 -->
                <div class="player-container">
                    <div class="xgplayer-wrapper">
                        <div id="h5player" ref="player" class="xgplayer-container"></div>
                        <!-- 添加科技感边框 -->
                        <div class="tech-border top"></div>
                        <div class="tech-border bottom"></div>
                    </div>
                </div>
                <!-- 视频元信息 -->
                <div class="meta-section">
                    <el-row :gutter="20">
                        <el-col :xs="24" :sm="16">
                            <div class="video-header">
                                <div class="title-section">
                                    <h1 class="video-title">{{ video.title }}</h1>
                                    <el-button
                                        :type="isCollectedState ? 'danger' : 'primary'"
                                        @click="toggleCollect"
                                        class="collect-btn"
                                    >
                                        <el-icon>
                                            <component :is="isCollectedState ? Star : StarFilled" />
                                        </el-icon>
                                        {{ isCollectedState ? '取消收藏' : '收藏' }}
                                    </el-button>
                                </div>
                                
                            </div>

                            <div class="author-info">
                                <el-avatar :size="64" :src="video.avatar" />
                                <div class="author-detail">
                                    <h3>{{ video.username }}</h3>
                                    <div class="meta-stats">
                                        <span><el-icon>
                                                <View />
                                            </el-icon> {{ video.watchNums }}播放</span>
                                        <el-divider direction="vertical" />
                                        <span>{{ moment(video.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
                                    </div>
                                </div>
                            </div>
                        </el-col>

                    </el-row>

                </div>
            </div>

        </el-main>

    </el-container>

    <!--个人信息对话框-->
  <el-dialog v-model="info" title="个人信息" width="500px"  class="custom-dialog">
    <el-form :model="form1" label-width="80px" style="padding: 10px;">
      <el-form-item label="头像">
        <div style="display: flex; align-items: center;">
          <el-avatar :src="form1.avatar" :icon="UserFilled" style="background-color: #8ac8ff; margin-right: 10px;" />
          <el-upload
              :on-change="handleAvatarChange"
              :auto-upload="false"
              :show-file-list="false"
              :file-list="fileList">
            <el-button size="small" type="primary">修改头像</el-button>
          </el-upload>
        </div>
      </el-form-item>

      <el-form-item label="用户名">
        <el-input v-model="form1.username" autocomplete="off" placeholder="请输入用户名" style="width: 130px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="text-align: right;">
        <el-button @click="info = false">取消</el-button>
        <el-button type="primary" @click="saveInfo">保存</el-button>
      </div>
    </template>
  </el-dialog>

    <!--修改密码对话框-->
    <el-dialog v-model="password" title="修改密码" width="500px" class="custom-dialog">
        <el-form :model="form2" label-width="80px" style="padding: 10px;">
            <el-form-item label="旧密码">
                <el-input type="password" v-model="form2.password" autocomplete="off" placeholder="请输入旧密码"
                    style="width: 200px" />
            </el-form-item>
            <el-form-item label="新密码">
                <el-input type="password" v-model="form2.newPassword" autocomplete="off" placeholder="请输入新密码"
                    style="width: 200px" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer" style="text-align: right;">
                <el-button @click="password = false">取消</el-button>
                <el-button type="primary" @click="savePassword">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>


<style lang="scss" scoped>
$primary-blue: #409EFF;
$hover-blue: rgba(64, 158, 255, 0.1);

/* 容器强化全屏居中 */
.order-card-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: calc(100vh - 60px);
    width: 100%;
    padding: 20px;
}

/* 卡片主体 */
.order-card {
    width: 800px;
    margin: 0 auto;
    min-height: 500px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    border-radius: 12px;
    padding: 30px;

    /* 标题区域右对齐 */
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 30px;

        .el-tag {
            margin-left: auto;
            order: 2;
        }
    }

    /* 按钮居中 */
    .action-buttons {
        margin-top: 40px;
        display: flex;
        justify-content: center;
        gap: 20px;

        .el-button {
            width: 160px;
            margin: 0 !important;
        }
    }
}

/* 响应式适配 */
@media screen and (max-width: 768px) {
    .order-card {
        width: 95%;
        padding: 20px;

        .card-header h2 {
            font-size: 22px !important;
        }
    }
}

.player-container {
    position: relative;
    max-width: 1200px;
    /* 新增最大宽度限制 */
    margin: 20px auto;
    /* 垂直间距+水平居中 */
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    /* 增强立体感 */
    background: linear-gradient(145deg, #1a1a1a 0%, #2d2d2d 100%);
    /* 渐变背景 */
    margin-bottom: 30px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: #000;
    transition: all 0.3s ease;
}

.player-container:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.tech-border {
    position: absolute;
    height: 4px;
    background: linear-gradient(90deg, transparent, #00ffd9, transparent);
    filter: drop-shadow(0 0 8px #00ffd9);
}

.tech-border.top {
    top: 0;
    width: 100%;
}

.tech-border.bottom {
    bottom: 0;
    width: 100%;
}

.xgplayer-container {
    width: 800px;
    /* 固定宽度 */
    height: 450px;
    /* 16:9比例 */
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.meta-section {
    max-width: 1200px;
    /* 新增最大宽度限制 */
    margin: 20px auto;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.video-title {
    font-size: 2rem;
    color: #2c3e50;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.author-info {
    display: flex;
    align-items: center;
    gap: 16px;

    .author-detail {
        h3 {
            margin: 0;
            color: #34495e;
        }

        .meta-stats {
            color: #7f8c8d;
            font-size: 0.9rem;

            .el-icon {
                vertical-align: middle;
            }
        }
    }
}

.action-panel {
    display: flex;
    gap: 12px;
    justify-content: flex-end;

    .el-button {
        padding: 12px 24px;
        border-radius: 6px;
    }
}

@media (max-width: 768px) {
    .video-title {
        flex-direction: column;
        align-items: flex-start;

        .el-tag {
            margin-left: 0 !important;
            margin-top: 8px;
        }
    }

    .action-panel {
        justify-content: flex-start;
        margin-top: 20px;
    }
}

.home-container {
    background: #fff;
    min-height: 100vh;

    /* 容器布局 */
    .header {
        height: 70px !important;
        background: #ffffff;
        /* 纯白背景替代毛玻璃 */
        border-bottom: 1px solid #ebeef5;
    }

    .nav-container {
        max-width: 1440px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        height: 100%;
        padding: 0 24px;
    }

    /* Logo样式 */
    .logo {
        font-size: 24px;
        font-weight: 600;
        margin-right: 48px;
        color: #303133;
    }

    .logo .blue {
        color: #409eff;
    }

    /* 导航菜单核心配置 */
    .el-menu--horizontal {
        background: transparent !important;
        border-bottom: none !important;
        flex: 1;
    }

    .el-menu-item {
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        padding: 0 28px;
        color: #606266;
        transition: color 0.3s;
    }

    .el-menu-item.is-active {
        color: #409eff !important;
        border-bottom: 2px solid #409eff;
    }

    /* 搜索框定制 */
    .search-box {
        margin-left: auto;
        margin-right: 24px;
    }

    .search-box .el-input {
        --el-input-border-radius: 20px;
        --el-input-bg-color: #f5f7fa;
    }

    .search-box .el-input__wrapper {
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    }

    /* 用户面板 */
    .user-panel .el-button {
        border-radius: 20px;
        padding: 10px 24px;
        background: #409eff;
        color: white;
    }

    .main-content {
        max-width: 1400px; // 扩大容器宽度
        width: 98%; // 增加自适应能力

        .course-section {
            .el-col {
                @media (min-width: 1200px) {
                    flex: 0 0 25%; // 大屏显示4列课程卡片
                    max-width: 25%;
                }
            }
        }

        margin: 0 auto;
        padding: 20px;



        .category-sidebar {
            .section-title {
                color: #303133;
                font-size: 20px;
                margin-bottom: 15px;
            }

            .category-item {
                display: flex;
                align-items: center;
                padding: 7px;
                transition: all 0.3s;

                &:hover {
                    background: #f8f9fa;
                    transform: translateX(5px);
                }

                .icon-box {
                    width: 40px;
                    height: 40px;
                    border-radius: 8px;
                    margin-right: 15px;
                }

                .cate-name {
                    font-size: 16px;
                    color: #606266;
                }
            }
        }

        // .main-section {
        //   margin-bottom: 40px;
        // }

        // .compact-carousel {

        //   border-radius: 8px;
        //   overflow: hidden;
        //   box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

        //   .carousel-slide {
        //     height: 100%;
        //     display: flex;
        //     align-items: center;
        //     justify-content: center;
        //     background: linear-gradient(135deg, #409EFF, #79bbff);

        //     h2 {
        //       color: white;
        //       font-size: 28px;
        //       text-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
        //     }
        //   }
        // }

        /* 轮播容器优化 */
        .enhanced-carousel {
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        /* 轮播项容器 */
        .carousel-slide {
            position: relative;
            width: 100%;
            height: 100%;
        }

        /* 图片容器 */
        .image-wrapper {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        /* 图片填充处理 */
        .carousel-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            /* 保持比例填充容器 */
            object-position: center;
            /* 图片中心裁剪 */
            transition: transform 0.3s ease;
        }

        /* 悬浮标题样式 */
        .floating-title {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px 30px;
            background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
            color: white;
        }

        .title-text {
            margin: 0;
            font-size: 1.5em;
            text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5);
        }

        /* 指示器样式优化 */
        :deep(.el-carousel__indicators--outside) {
            bottom: 40px;
            /* 调整指示器位置 */
        }


        /* 悬停效果 */
        @media (hover: hover) {
            .carousel-image:hover {
                transform: scale(1.03);
            }
        }

        .course-section {
            .section-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 30px;
            }

            .course-card {
                transition: all 0.3s;
                margin: 0 10px 15px; // 增加左右间距
                width: calc(100% - 20px); // 防止溢出

                &:hover {
                    transform: translateY(-5px);
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                }

                .course-cover {
                    height: 180px;
                    background: #909399;
                    border-radius: 4px;
                    margin-bottom: 15px;
                }

                .title {
                    color: #303133;
                    font-size: 16px;
                    margin-bottom: 12px;
                }

                .meta {
                    display: flex;
                    justify-content: space-between;
                    color: #909399;

                    .price {
                        color: #F56C6C;
                        font-weight: bold;
                    }
                }
            }
        }
    }
}

.video-header {
    margin-bottom: 20px;
    
    .title-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        .video-title {
            margin: 0;
            font-size: 24px;
            color: #303133;
        }
        
        .collect-btn {
            margin-left: 20px;
        }
    }
    
    .video-meta {
        color: #909399;
        font-size: 14px;
        
        span {
            margin-right: 20px;
            
            &:last-child {
                margin-right: 0;
            }
        }
    }
}
</style>
